package com.wushijia.highconcurrency;

import java.util.concurrent.TimeUnit;

/**
 * 测试修改volatile修饰的变量，可以被其他线程感知
 */
public class VolatileTest {

  static volatile int INIT_VALUE = 5;

  final static int MAX_VALUE = 10;

  public static void main(String[] args) {


    new Thread(() -> {
      int localValue = INIT_VALUE;
      while (localValue < MAX_VALUE) {
          if (INIT_VALUE != localValue) {
          System.out.printf("The value will be updated to {%d} \n", INIT_VALUE);
          localValue = INIT_VALUE;
        }
      }
    }, "Reader").start();


    new Thread(() -> {
      int localValue = INIT_VALUE;
      while (localValue < MAX_VALUE) {
        System.out.printf("The value will be changed to {%d} \n", ++localValue);
        INIT_VALUE = localValue;

        try {
          TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

    }, "Updater").start();
  }
}
